Crate jzon

source ·
Expand description

json-rust

Parse and serialize JSON with ease.

Changelog - Complete Documentation - Cargo - Repository

Why?

JSON is a very loose format where anything goes - arrays can hold mixed types, object keys can change types between API calls or not include some keys under some conditions. Mapping that to idiomatic Rust structs introduces friction.

This crate intends to avoid that friction.

let parsed = jzon::parse(r#"

{
    "code": 200,
    "success": true,
    "payload": {
        "features": [
            "awesome",
            "easyAPI",
            "lowLearningCurve"
        ]
    }
}

"#).unwrap();

let instantiated = object!{
    // quotes on keys are optional
    "code": 200,
    success: true,
    payload: {
        features: [
            "awesome",
            "easyAPI",
            "lowLearningCurve"
        ]
    }
};

assert_eq!(parsed, instantiated);

First class citizen

Using macros and indexing, it’s easy to work with the data.

let mut data = object!{
    foo: false,
    bar: null,
    answer: 42,
    list: [null, "world", true]
};

// Partial equality is implemented for most raw types:
assert!(data["foo"] == false);

// And it's type aware, `null` and `false` are different values:
assert!(data["bar"] != false);

// But you can use any Rust number types:
assert!(data["answer"] == 42);
assert!(data["answer"] == 42.0);
assert!(data["answer"] == 42isize);

// Access nested structures, arrays and objects:
assert!(data["list"][0].is_null());
assert!(data["list"][1] == "world");
assert!(data["list"][2] == true);

// Error resilient - accessing properties that don't exist yield null:
assert!(data["this"]["does"]["not"]["exist"].is_null());

// Mutate by assigning:
data["list"][0] = "Hello".into();

// Use the `dump` method to serialize the data:
assert_eq!(data.dump(), r#"{"foo":false,"bar":null,"answer":42,"list":["Hello","world",true]}"#);

// Or pretty print it out:
println!("{:#}", data);

Serialize with jzon::stringify(value)

Primitives:

// str slices
assert_eq!(jzon::stringify("foobar"), "\"foobar\"");

// Owned strings
assert_eq!(jzon::stringify("foobar".to_string()), "\"foobar\"");

// Any number types
assert_eq!(jzon::stringify(42), "42");

// Booleans
assert_eq!(jzon::stringify(true), "true");
assert_eq!(jzon::stringify(false), "false");

Explicit null type jzon::Null:

assert_eq!(jzon::stringify(jzon::Null), "null");

Optional types:

let value: Option<String> = Some("foo".to_string());
assert_eq!(jzon::stringify(value), "\"foo\"");

let no_value: Option<String> = None;
assert_eq!(jzon::stringify(no_value), "null");

Vector:

let data = vec![1,2,3];
assert_eq!(jzon::stringify(data), "[1,2,3]");

Vector with optional values:

let data = vec![Some(1), None, Some(2), None, Some(3)];
assert_eq!(jzon::stringify(data), "[1,null,2,null,3]");

Pushing to arrays:

let mut data = jzon::JsonValue::new_array();

data.push(10);
data.push("foo");
data.push(false);

assert_eq!(data.dump(), r#"[10,"foo",false]"#);

Putting fields on objects:

let mut data = jzon::JsonValue::new_object();

data["answer"] = 42.into();
data["foo"] = "bar".into();

assert_eq!(data.dump(), r#"{"answer":42,"foo":"bar"}"#);

array! macro:

let data = array!["foo", "bar", 100, true, null];
assert_eq!(data.dump(), r#"["foo","bar",100,true,null]"#);

object! macro:

let data = object!{
    name: "John Doe",
    age: 30,
    canJSON: true
};
assert_eq!(
    data.dump(),
    r#"{"name":"John Doe","age":30,"canJSON":true}"#
);

Re-exports

  • pub use value::JsonValue::Null;
  • pub use Error as JsonError;
  • pub use crate::Result as JsonResult;

Modules

Macros

  • Helper macro for creating instances of JsonValue::Array.
  • Helper macro for creating instances of JsonValue::Object.
  • Helper crate for converting types into JsonValue. It’s used internally by the object! and array! macros.

Enums

Functions

  • Convenience for JsonValue::from(value)
  • Pretty prints out the value as JSON string.
  • Pretty prints out the value as JSON string. Second argument is a number of spaces to indent new blocks with.

Type Aliases